package com.woniuxy.educationplatform.realm;

import com.woniuxy.educationplatform.bean.AdminBean;
import com.woniuxy.educationplatform.service.IAdminService;
import com.woniuxy.educationplatform.service.ISystemService;
import com.woniuxy.educationplatform.util.InitByteSource;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author unreleased
 * @date 2020/12/8 17:21
 * 自定义realm 需要指定数据从哪儿来
 * AuthorizingRealm : 授权领域
 * Authentication:验证
 */
public class LoginAndAuthorizationRealm extends AuthorizingRealm {
    @Autowired
    private ISystemService systemServiceImpl;

    @Autowired
    private IAdminService adminService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权开始");
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        AdminBean user = (AdminBean)session.getAttribute("user");
        //根据session登录名查询角色相关信息
        AdminBean admin = adminService.findAdminByLoginName(user.getLoginName());
        //定义一个授权信息对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole(admin.getRoleBean().getRoleName());
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("开始认证");
        String loginName = (String) token.getPrincipal();
        AdminBean adminBean = systemServiceImpl.login(loginName);
        if(adminBean  == null){
            return null;
        }
        //如果用户存在，将该用户装配到Shiro的session中
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("user",adminBean);

        ByteSource byteSource = new InitByteSource(loginName);

        //返回信息认证信息 登录名、密码、域的名称
        return new SimpleAuthenticationInfo(loginName,adminBean.getPassword(),byteSource,getName());
    }
}
